<?php
if ( !defined('IN_ADMINCP') || !defined('IN_SEC') ){
	exit('Access Denied.');
}

$id = abs(intval($_G['gp_id']));

if( $id ){
	if( !$department = fetch('admincp_department', $id) ){
		$admincp->cpmsg('部门不存在');
	}
}

$companyid = abs(intval($_G['gp_companyid']));

$companys = limitquery('companys');
$where = array();

$where['companyid'] = 0;

if( $department['companyid'] ){
	unset($where['companyid']);
	$where[] = "`companyid` = 0 OR `companyid` = {$department['companyid']}";
}

if( $companyid ){
	unset($where['companyid']);
	$where[] = "`companyid` = 0 OR `companyid` = {$companyid}";
}

$departments = limitquery('admincp_department', $where);

if( is_post() ){
	if( !confirm_password($admincp->admin) ){
		$admincp->cpmsg('密码不正确！授权操作失败！');
	}

	$name = $_G['gp_name'] ? htmlspecialchars($_G['gp_name']) : $admincp->cpmsg('部门名称不能为空！');
	$companyid = $_G['gp_companyid'] ? $_G['gp_companyid'] : 0;
	$parentid = $_G['gp_parentid'] ? $_G['gp_parentid'] : 0;

	$update = array(
		'name' => $name,
		'companyid' => $companyid,
		'parentid' => $parentid
	);

	if( $department ){
		update('admincp_department', $department['id'], $update);
	}else{
		$update['create_time'] = SYS_TIME;
		DB::Insert('admincp_department', $update);
	}
	$admincp->success('操作成功');
}

?>